<template>
  <el-tabs
    closable
    type="card"
    v-model="currentTab.name"
    class="demo-tabs"
    @tab-click="handleClick"
    @tab-remove="remove"
  >
    <el-tab-pane
      :label="item.name"
      :name="item.name"
      v-for="item in tabs"
      :key="item.name"
    >
      <template #label>
        <span class="custom-tabs-label">
          <el-icon>
            <component :is="item.icon"></component>
          </el-icon>
          <span>&nbsp;{{ item.name }}</span>
        </span>
      </template></el-tab-pane
    >
  </el-tabs>
  <RouterView v-slot="{ Component }">
    <KeepAlive>
      <component
        :is="Component"
        :key="$route.name"
        v-if="$route.meta.KeepAlive"
      ></component>
    </KeepAlive>
    <component
      :is="Component"
      :key="$route.name"
      v-if="!$route.meta.KeepAlive"
    ></component>
  </RouterView>
</template>

<script lang="ts" setup>
import { useTabsStore } from '@/store/tabs.ts';
import { storeToRefs } from 'pinia';
import { useRouter, useRoute } from 'vue-router';
import { useUserStore } from '@/store/auth';

const tabsStore = useTabsStore();
const userStore = useUserStore();
const router = useRouter();
const route = useRoute();
const { tabs, currentTab } = storeToRefs(tabsStore);
const { menu } = storeToRefs(userStore);
const { addTab, setCurrentTab, removeTab } = tabsStore;
const handleClick = ({ index }: { index: number }) => {
  setCurrentTab(tabs.value[index].name, tabs.value[index].url); // 设置当前高亮
  router.push(tabs.value[index].url); // 设置当前跳转
};

const remove = (tabPaneName: string) => {
  removeTab(tabPaneName);
  router.push(currentTab.value.url);
};

const findObjectByUrl = (arr: any[], url: string) => {
  for (const item of arr) {
    if (item.url === url) {
      return item;
    }
    if (item.children) {
      const found: any = findObjectByUrl(item.children, url);
      if (found) {
        return found;
      }
    }
  }
  return null;
};
const { name, url, icon } = findObjectByUrl(menu.value, route.path);
console.log('🚀 ~ name:', name);
addTab(name, url, icon);
setCurrentTab(name, url);
</script>

<style lang="less" scoped>
.demo-tabs {
  :deep(.is-active) {
    background-color: rgb(34, 135, 255) !important;
    color: #fff !important;
  }
}
</style>
